package main;
import javax.microedition.lcdui.Image;

import javax.microedition.lcdui.game.Sprite;

public class Bang extends javax.microedition.lcdui.game.Sprite {

    private int RATE = 5;
    protected int speedX = 10;
    protected int speedY = 10;
    private static final int NAIL_SPEED = 1;
    private int HEIGHT  ;
    private int WIDTH ;
    private static final int[] SEQUENCE = {18,19,20,21,22,23,24,25,26};
    private static final int MAX_HP = 100;
    private static final int DAMAGE_RATE =20;
    private int fireTick =0;
    private int current_HP = MAX_HP;
    private int SHOOT_RATE=30;
    private boolean destroyed = false;
    private int damagedTick;

    private Nail nail;
    public Bang(Image image, int w, int h) throws java.io.IOException {
        super(image,w ,h);
        WIDTH = w;
        HEIGHT= h;
        setFrameSequence(SEQUENCE);
        defineReferencePixel(WIDTH/2+1,HEIGHT/2);
        this.setTransform(this.TRANS_MIRROR_ROT270);
        this.setPosition(0, 0);
    }

    public void movement(){
        if(this.getY() < 40)
            this.move(0, 2);
    }

    public void initNail(Image image, int w, int h) throws java.io.IOException{
        nail = new Nail(image, w, h );
    }
    
    public void advance(int ticks) {
        if ((ticks%RATE==0))
            nextFrame();
    }

    public void moveLeft () {
        if (this.getRefPixelX()>0)
            this.move(-speedX, 0);
    }
    
    public void moveRight (int m) {
        if (this.getRefPixelX() < m)
            this.move(speedX, 0);
    }

    public void moveUp () {
        if (this.getRefPixelY()>0)
             this.move(0, -speedY/2);
    }
    
    public void moveDown (int m) {
        if (this.getRefPixelY()<m)
             this.move(0, speedY/2);
    }

    public Nail fire (int ticks) {

        if (ticks- fireTick > SHOOT_RATE) {
            fireTick = ticks;
            nail.setSpeed( NAIL_SPEED);
            nail.shot(this.getRefPixelX(), this.getRefPixelY()+HEIGHT/2);

            return nail;
        }
        else
            return null;
    }
    
    public void collided (int ticks, int damage) {
        if (!destroyed)
        if (ticks > damagedTick+DAMAGE_RATE ) {
            current_HP -=damage;
            if (current_HP <= 0) destroyed = true;
            damagedTick = ticks;
        }
    }

    public boolean isDestroyed () {
        return destroyed;
    }
    
    public double getHPPercentage() {
        if (!destroyed)
            return ((double)current_HP/(1.0*MAX_HP));
        else return 0;
    }

    public boolean isDamageable(int ticks) {
        return (ticks > damagedTick + DAMAGE_RATE);
    }
    
    public Nail getNail() {
        return nail;
    }
}
